package com.uenpay.im.broadcastreceiver;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.android.arouter.launcher.ARouter;
import com.qiyunxin.android.http.cache.HttpStreamCache;
import com.qyx.android.database.DBTopMsgColumns;
import com.qyx.android.database.FriendDB;
import com.qyx.android.database.GroupTalkDbManager;
import com.qyx.android.database.TopListMsgManager;
import com.qyx.android.entity.FriendEntity;
import com.qyx.android.entity.GroupTalkEntity;
import com.qyx.android.message.type.MsgContentType;
import com.qyx.android.message.type.PacketType;
import com.qyx.android.protocol.QyxMsg;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.configuration.ShareData;
import com.uenpay.im.ui.old.activity.videochat.VideoChatOffLineMsgManager;
import com.uenpay.im.ui.old.activity.videochat.VideoChatResponseActivity;
import com.uenpay.im.weight.RoundImageView;
import com.uenpay.service.IPushMsgHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.MessageFormat;

/**
 * @author SL
 * @created 2016-2-29下午5:44:46
 * @copyRight http://www.qiyunxin.com
 */
public class PushMsgReceiverHandle {

    private VideoChatOffLineMsgManager mVideoChatOffLineMsgManager = new VideoChatOffLineMsgManager();
    private Context mContext;
    private TopListMsgManager topListMsgManager = null;
    private GroupTalkDbManager groupTalkDbManager = null;

    public PushMsgReceiverHandle(Context _Context) {
        mContext = _Context;
        groupTalkDbManager = new GroupTalkDbManager();
        topListMsgManager = new TopListMsgManager();
    }

    /**
     * @param message
     */
    public void answerVideoChat(QyxMsg message) {
        ActivityManager am = (ActivityManager) IMApplication.getAppContext().getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        if (cn.getClassName().equals(IMApplication.getInstance().getAppPackageName() + ".activity.videochat.CallActivity")
                || cn.getClassName().equals(
                IMApplication.getInstance().getAppPackageName() + ".activity.videochat.VideoChatResponseActivity")) {
            mVideoChatOffLineMsgManager.replyVideoChatMsg(message);
        } else {
            Intent intent = new Intent(mContext, VideoChatResponseActivity.class);
            intent.putExtra("message", message);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent);
        }
    }

    public boolean isCurrentChat(QyxMsg reciveMsg) {
        if (reciveMsg.sessionModel.getSessionType() == PacketType.GROUP) {
            if ((reciveMsg.sessionModel.getSessionId() + "").equals(ShareData.getInstance().getChatId())) {
                return true;
            } else {
                return false;
            }
        } else {
            long to_cust_id = 0;
            if ((reciveMsg.from_cust_id + "").equals(IMApplication.getCustId())) {
                to_cust_id = reciveMsg.to_cust_id;
            } else {
                to_cust_id = reciveMsg.from_cust_id;
            }
            if ((to_cust_id + "").equals(ShareData.getInstance().getChatId())) {
                return true;
            } else {
                return false;
            }
        }
    }

    public void showNotification(String chat_id, int num, String from_cust_name, String content, QyxMsg message, int info_id, int module_id) {
        IMApplication.notification_sum += num;
        int notify_num = IMApplication.notification_sum;

        String tip = "";

        if (content.length() > 30) {
            tip = content.substring(0, 30) + "...";
        } else {
            tip = content;
        }

        if (!TextUtils.isEmpty(from_cust_name)) {
            tip = from_cust_name + " : " + tip;
        }

        showSysNotification(chat_id, IMApplication.getInstance().getAppPackageName() + ".activity.MainActivity", 0, mContext, mContext
                        .getResources().getString(R.string.app_name), MessageFormat.format(
                mContext.getResources().getString(R.string.unread_msg_tip), notify_num), tip, System.currentTimeMillis(), message, info_id,
                module_id);
    }

    @SuppressLint("InlinedApi")
    private void showSysNotification(String chat_id, String activityName, int intentType, Context context, String contentTitle,
                                     String ticket, String contentText, long when, QyxMsg message, int info_id, int module_id) {
        Log.d("liulou", "showSysNotification: ");
        Intent intent = ((IPushMsgHelper) (ARouter.getInstance().build("/push/pushMsgHelper").navigation())).getIntent(context);
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.putExtra("notification", true);
        intent.putExtra("category", message.msg_content_type);
        intent.putExtra("msg_type", message.msg_type);
        intent.putExtra("info_id", info_id);
        intent.putExtra("module_id", module_id);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        int request_code = 0;
        if (message.msg_content_type == MsgContentType.NEWS) {
            request_code = 1;
        } else if (message.msg_content_type == MsgContentType.FRIEND_INVITE) {
            request_code = 2;
        }
        PendingIntent contentIntent = PendingIntent.getActivity(context, request_code, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        Bitmap bitmap = BitmapFactory.decodeResource(IMApplication.getAppContext().getResources(), R.drawable.notification_ic_launcher);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.notification_ic_launcher)
                .setLargeIcon(bitmap).setContentTitle(contentTitle).setContentText(contentText).setTicker(ticket).setAutoCancel(true)
                .setContentIntent(contentIntent).setWhen(when).setOngoing(true);
        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        int is_sound = IMApplication.config.getMsgVoice();
        int is_shock = IMApplication.config.getMsgShake();
        int new_msg_notice = IMApplication.config.getMsgNotice();

        if (!TextUtils.isEmpty(chat_id) && !chat_id.equals("0")) {

            GroupTalkEntity groupTalk = groupTalkDbManager.queryGroupByGroupId(Long.valueOf(chat_id));

            if (groupTalk.is_remind == 1) {
                new_msg_notice = 0;
            }
        } else {
            FriendEntity entity = FriendDB.getFriend(message.from_cust_id + "");
            if (entity != null) {
                if (entity.is_remind == 1) {
                    new_msg_notice = is_sound = is_shock = 0;
                }
            }
        }

        if (is_sound == 1) {
            builder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS);
        }
        boolean is_at = false;
        if (message.content.indexOf("@" + IMApplication.config.getUserName()) != -1) {
            is_at = true;
        }

        long[] vibreate = new long[]{500, 500};
        if (is_shock == 1 || is_at) {
            builder.setVibrate(vibreate);
            builder.setDefaults(Notification.DEFAULT_LIGHTS);
        }

        if ((is_shock == 1 && is_sound == 1) || is_at) {
            builder.setVibrate(vibreate);
            builder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS);
        }

        if (is_shock == 0 && is_sound == 0) {
            builder.setDefaults(Notification.DEFAULT_LIGHTS);
        }
        if (new_msg_notice == 1 || is_at) {
            Notification notify = builder.build();
            notify.flags = Notification.FLAG_AUTO_CANCEL;
            mNotificationManager.notify(request_code, notify);
        }
        if (bitmap != null && !bitmap.isRecycled())
            bitmap.recycle();
    }

    /**
     * 收到对方撤销消息
     *
     * @param message
     */
    public void receiveWithdrawMsg(QyxMsg message) {
        if (message.sessionModel.getSessionType() == PacketType.GROUP && message.from_cust_id == Long.valueOf(IMApplication.getCustId())) {
            return;
        }
        String msg_no = "";
        if (!TextUtils.isEmpty(message.content_json)) {
            try {
                JSONObject jsonObject = new JSONObject(message.content_json);
                if (jsonObject != null && jsonObject.has("msgno")) {
                    msg_no = jsonObject.optString("msgno");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        Intent intent = new Intent(BroadcastAction.ACTION_WITHDRAW_MSG);
        intent.putExtra("msg_no", msg_no);
        IMApplication.getAppContext().sendBroadcast(intent);
    }

    /**
     * 收到对方删除登录用户消息
     *
     * @param message
     */
    public void receiveDeleteFriend(QyxMsg message) {
        FriendDB.deleteFriend(message.from_cust_id + "");
        // topListMsgManager
        // .deleteByMsg(message.from_cust_id, PacketType.PERSONAL);
        // talkMsgManager.deleteSingleChatMsg(message.from_cust_id,
        // Long.valueOf(MyApplication.getCustId()));
        Intent intent = new Intent(BroadcastAction.DELETE_FRIEND_ACTION);
        IMApplication.getAppContext().sendBroadcast(intent);
    }

    /**
     * 收到动态评论
     *
     * @param message
     */
    public void receiveDynamicNewReply(QyxMsg message) {
        IMApplication.config.setDynamicUnreadMsgCustId(message.from_cust_id + "");
        int num = IMApplication.config.getDynamicUnreadMsgCount();
        num++;
        IMApplication.config.setDynamicUnreadMsgCount(num);
        Intent intent = new Intent(BroadcastAction.DISCOVER_UNREAD_COUNT_ACTION);
        IMApplication.getAppContext().sendBroadcast(intent);
    }

    /**
     * 新动态发布
     *
     * @param message
     */
    public void receiveDynamicNewPublish(QyxMsg message) {
        IMApplication.config.setDynamicLastSendCustId(message.from_cust_id + "");
        Intent intent = new Intent(BroadcastAction.DISCOVER_UNREAD_COUNT_ACTION);
        IMApplication.getAppContext().sendBroadcast(intent);
    }

    /**
     * 头像更新消息
     *
     * @param message
     * @param msgContentType
     */
    public void receivePhotoUpdate(QyxMsg message, int msgContentType) {
        int packetType = PacketType.PERSONAL;
        if (msgContentType == MsgContentType.GROUP_TALK_PHOTO_UPDATE) {
            packetType = PacketType.GROUP;
        }
        String small = APIConfiguration.getAvatarUrlNormal(message.from_cust_id + "", packetType);
        String big = APIConfiguration.getAvatarUrlBig(message.from_cust_id + "", packetType);
        HttpStreamCache.getInstance().ClearCacheBitmap(small);
        HttpStreamCache.getInstance().ClearCacheBitmap(big);
        IMApplication.getAppContext().sendBroadcast(new Intent(BroadcastAction.ACTION_REFRESH_AVATAR));
        RoundImageView imageView = new RoundImageView(mContext);
        imageView.SetUrl(small);
    }

    /**
     * 收到@消息类型
     *
     * @param message
     */
    public void receivedAtMsg(QyxMsg message) {
        long chat_id = 0;
        if (message.sessionModel.getSessionType() == PacketType.PERSONAL) {
            chat_id = message.from_cust_id;
        } else {
            chat_id = message.sessionModel.getSessionId();
        }
        topListMsgManager.updateTopMsgByField(chat_id, message.sessionModel.getSessionType(), DBTopMsgColumns.IS_AT, "1");
    }

}
